package is.glif.fenius.webui.topo;


import java.io.File;
import java.util.HashMap;

import org.apache.cxf.helpers.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FileGroupProvider implements GroupProvider {
    private static FileGroupProvider instance;
    public static FileGroupProvider getInstance() {
        if (instance == null) {
            instance = new FileGroupProvider();
        }
        return instance;
    }
    private FileGroupProvider() {
        this.refresh();
    }
    private String directory = "./config/groups"; 
    private HashMap<String, Long> lastLoaded = new HashMap<String, Long>();
    private HashMap<String, String> fileContents = new HashMap<String, String>();

    public void refresh() {
        Long now = System.currentTimeMillis();
        File folder = new File(directory);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            File file = listOfFiles[i];
            if (file.isFile()) {
                String fileName = file.getName();
                Long modified = file.lastModified();
                boolean reload = false;
                if (!lastLoaded.containsKey(fileName)) {
                    reload = true;
                } else if (lastLoaded.get(fileName) < modified) {
                    reload = true;
                }
                if (reload) {
                    System.out.println("reloading "+fileName);
                    String jsonString = FileUtils.getStringFromFile(file);
                    lastLoaded.put(fileName, now);
                    fileContents.put(fileName, jsonString);
                }
            }
        }
    }

    public JSONArray getGroups(String network, String match) throws JSONException {
        JSONArray result = new JSONArray();
        match = match.replace("*", "");
        this.refresh();
        for (String jsonString : fileContents.values()) {
            JSONArray tmp = new JSONArray(jsonString);
            for (int j  = 0; j < tmp.length(); j++) {
                JSONObject obj = tmp.getJSONObject(j);
                String thisNet = obj.getString("network");
                String thisName = obj.getString("name");
                if (thisNet.equals(network)) {
                    if (match.equals("") || thisName.startsWith(match)) {
                        result.put(obj);
                    }
                }
            }
        }
        return result;
    }

}
